package com.scribbles.common.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.scribbles.common.exception.ScribblesRuntimeException;

public class BaseController {

	Logger logger = Logger.getLogger(BaseController.class);
	
	@ExceptionHandler(ScribblesRuntimeException.class)
	public void handleScribblesRuntimeException(ScribblesRuntimeException sre,
			HttpServletResponse response) {
		PrintWriter pw = null;
		StringBuffer st = new StringBuffer(32);

		logger.info("Exception DetailedMessage : " + sre.getDetailedMessage());
		response.setContentType("application/json");
		try {
			pw = response.getWriter();

		st.append('{');
		st.append("failure:true,");
		st.append("message:");
		st.append('\'');
		st.append(sre.getMessage());
		st.append('\'');
		if (null != sre.getDetailedMessage()) {
			st.append(',');
			st.append("detailedMessage:");
			st.append('\'');
			st.append(sre.getDetailedMessage());
			st.append('\'');
		}
		if (null != sre.getException()) {
			st.append(',');
			st.append("exceptionStackTrace:");
			st.append('\'');
			st.append(sre.getException().getStackTrace());
			st.append('\'');
		}
		st.append('}');

		pw.write(st.toString());
		} catch (RuntimeException e) { // $codepro.audit.disable
			logger.error("Error while getting reference of PrintWriter to log the messages");
		} catch (IOException e) { // $codepro.audit.disable
			logger.error("Error IOException");
		} finally {
			pw.close();
		}
		

		/*
		 * Map<String, Object> modelMap = new HashMap<String, Object>();
		 * modelMap.put("failure", true); modelMap.put("message",
		 * sre.getMessage()); modelMap.put("detailedMessage",
		 * sre.getDetailedMessage()); modelMap.put("exceptionStackTrace",
		 * sre.getException().getStackTrace()); return modelMap;
		 */
	}

}
